from socket import *
try:
    from typing import Optional
except ImportError:
    pass
from bootstrap.configs import UDP_DISCOVERY_PORT

class UDPSender:
    def __init__(self) -> None:
        
        self._th = None
        self.port = UDP_DISCOVERY_PORT
        # 缓存UDP套接字
        self.socket: "Optional[socket]" = None

    def send(self, target_ip: str, message: bytes) -> None:
        if not self.socket:
            self.socket = socket(AF_INET, SOCK_DGRAM)
        self.socket.sendto(message, (target_ip, self.port))

    def close(self) -> None:
        if self.socket is not None:
            self.socket.close()


onboard_sender = UDPSender()
